package org.example.com.zwh.service;

import io.seata.spring.annotation.GlobalTransactional;
import org.example.com.zwh.entity.Order;
import org.example.com.zwh.entity.SeckillOrder;
import org.example.com.zwh.mapper.OrderMapper;
import org.example.com.zwh.mapper.SeckillOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@Service
public class SeckillService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    // 原子减库存
    @GlobalTransactional(name = "seckill_tx_group", rollbackFor = Exception.class)
    public long decrementStock(String userId, String productId) {
        String key = "seckill:stock:" + productId;
        //首先查询redis是否存在该商品
        Long stock = redisTemplate.opsForValue().decrement(key);    // 原子减库存
        if (stock == null) {
            //如果不存在，返回失败
            throw new RuntimeException("库存操作失败");
        }
        if (stock != null && stock < 0) {
            redisTemplate.opsForValue().increment(key); // 回滚库存
            throw new RuntimeException("库存不足");
        }
        //如果存在，更新redis库存
        if (stock >= 0) {
            //生成秒杀订单
            SeckillOrder seckillOrder = new SeckillOrder();
            //生成订单号uuid
            seckillOrder.setId(UUID.randomUUID().toString());
            seckillOrder.setUserId(userId);
            seckillOrder.setActivityId(productId);
            seckillOrder.setStatus("1");
            seckillOrder.setCreateTime(LocalDateTime.now());
            seckillOrderMapper.insert(seckillOrder);
        }
        return stock;

    }
    // 队列操作使用列表类型（需要新增队列操作方法）
    public void pushToQueue(Map<String, String> task) {
        redisTemplate.opsForList().leftPush("seckill:queue", task); // 正确使用列表操作
    }
    
    // 用户验证逻辑
    public boolean validateUser(String userId) {
        String userKey = "seckill:user:" + userId;
        // 限制每个用户只能参与一次
        return redisTemplate.opsForValue().setIfAbsent(userKey, "1", Duration.ofHours(2));
    }

    public void deleteTask(String userId, String productId) {
        seckillOrderMapper.deleteByUserIdAndActivityId(userId, productId);
    }

    public void updateOrderStatus(String userId, String productId, String i) {
        SeckillOrder seckillOrder = seckillOrderMapper.getSeckillOrderByUserIdAndActivityId(userId, productId);
        seckillOrder.setStatus("3");
        seckillOrderMapper.updateById(seckillOrder.getId(), seckillOrder.getStatus());

    }


}
